<template>
  <div>
    <!-- 页面标题 -->
    <div style="font-size: 24px; font-weight: bold; margin-bottom: 20px;">
      帖子发布管理
    </div>

    <!-- 分类筛选区域 -->
    <div class="category-filter-area">
      <div class="category-title">分类</div>
      <div class="category-divider"></div>
      <div class="category-buttons">
        <button
          class="category-btn"
          :class="{ active: activeCategory === '' }"
          @click="filterByCategory('')"
        >
          全部
        </button>
        <button
          v-for="item in courseList"
          :key="item.courseId"
          class="category-btn"
          :class="{ active: activeCategory === item.courseName }"
          @click="filterByCategory(item.courseName)"
        >
          {{ item.courseName }}
        </button>
      </div>
      <div class="category-divider"></div>
    </div>

    <!-- 搜索框 -->
    <el-input
      placeholder="搜索主题ID"
      v-model="searchQuery"
      style="width: 300px; float: right; margin-bottom: 20px;"
      @keyup.enter="searchTopics"
    >
      <template #append>
        <el-button
          icon="el-icon-search"
          @click="searchTopics"
          class="search-button"
        >
          搜索
        </el-button>
      </template>
    </el-input>

    <!-- 清除浮动 -->
    <div style="clear: both;"></div>

    <!-- 遍历 topics 显示主题信息 -->
    <el-card v-for="topic in topics" :key="topic.topicId" style="margin-bottom: 20px">
      <div style="display: flex; align-items: flex-start;">
        <div style="flex: 1;">
          <!-- 标题 -->
          <div style="font-size: 18px; font-weight: bold; margin-bottom: 5px;">
            {{ topic.title || 'No Title' }}
          </div>
          <!-- 用户ID -->
          <div style="font-size: 14px; color: #666; margin-bottom: 10px;">
            用户ID: {{ topic.userId || 'N/A' }}
          </div>
          <!-- 科目 -->
          <div style="font-size: 14px; color: #666; margin-bottom: 10px;">
            科目: {{ topic.courseName || 'N/A' }}
          </div>
          <!-- 内容 -->
          <div style="margin-bottom: 10px;" v-html="topic.content || 'No Content'">
          </div>
        </div>
        <!-- 按钮区域 -->
        <div style="display: flex; flex-direction: column; align-items: flex-end;">
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            @click="deleteTopic(topic.topicId)"
            class="button"
            style="margin-bottom:20px;"
          >
            删除
          </el-button>
          <!-- 评论详情按钮 -->
          <el-button
            type="primary"
            @click="showComments(topic.topicId)"
            class="button"
          >
            评论详情
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 分页控件 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="fetchTopics"
      />
    </div>

    <!-- 评论详情对话框 -->
    <el-dialog v-model="dialogVisible" title="用户评论">
      <div style="clear: both;"></div>
      <!-- 遍历 comments 显示评论信息 -->
      <div
        v-for="comment in comments"
        :key="comment.commentId"
        class="comment-item"
      >
        <div class="comment-header">
          <!-- 评论者ID -->
          <span class="commenter-id">评论者ID: {{ comment.comment_user_id || 'N/A' }}</span>
        </div>
        <div class="comment-content">
          <!-- 评论内容 -->
          <div v-html="comment.comment_content || 'No Comment'"></div>
          <!-- 评论创建时间 -->
          <span class="comment-time">{{ comment.comment_create_time || 'N/A' }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      topics: [], // 存储主题信息
      comments: [], // 存储评论信息
      dialogVisible: false, // 控制评论对话框的显示隐藏
      searchQuery: '', // 搜索框的值
      total: 0, // 总条目数
      pageSize: 8, // 每页显示的条目数
      currentPage: 1, // 当前页码
      courseList: [], // 课程列表
      activeCategory: '', // 当前选中的分类
    };
  },
  created() {
    this.fetchTopics(); // 页面创建时获取主题列表
    this.fetchCourseList(); // 获取课程列表
  },
  methods: {
    // 获取课程列表
    async fetchCourseList() {
      try {
        const response = await axios.get('http://localhost:8080/Courses/all');
        this.courseList = response.data || [];
      } catch (error) {
        console.error('获取课程列表失败:', error);
        this.$message.error('获取课程列表失败');
      }
    },
    // 根据分类筛选主题
    filterByCategory(courseName) {
      this.activeCategory = courseName;
      this.currentPage = 1;
      this.fetchTopics();
    },
    // 获取主题列表及其评论
    async fetchTopics(page = this.currentPage) {
      try {
        const params = {
          page,
          size: this.pageSize,
        };
        if (this.activeCategory) {
          params.courseName = this.activeCategory;
        }
        if (this.searchQuery) {
          params.topicId = parseInt(this.searchQuery) || 0;
        }
        const response = await axios.get('http://localhost:8080/topic/list-with-course', {
          params,
        });
        this.topics = response.data.list || [];
        this.total = response.data.total || 0;
      } catch (error) {
        console.error('获取帖子列表失败:', error);
        this.$message.error('获取帖子列表失败');
      }
    },
    // 根据 topic_id 获取评论
    async showComments(topicId) {
      try {
        const response = await axios.get(`http://localhost:8080/topic/with-comments-details`, {
          params: { topicId },
        });
        this.comments = response.data || [];
        this.dialogVisible = true;
      } catch (error) {
        console.error('获取评论失败:', error);
        this.$message.error('获取评论失败');
      }
    },
    // 搜索主题及其评论
    async searchTopics() {
      this.currentPage = 1;
      this.fetchTopics();
    },
    // 删除主题
    async deleteTopic(topicId) {
      try {
        await this.$confirm(`确定要删除帖子 ID: ${topicId} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const response = await axios.delete(`http://localhost:8080/topic/delete`, {
          params: { topicId }
        });

        if (response.data === 1) {
          this.$message.success('帖子删除成功');
          this.topics = this.topics.filter(topic => topic.topicId !== topicId);
          this.total -= 1;
        } else {
          this.$message.error('删除帖子失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除帖子失败:', error);
          const errorMsg = error.response?.data?.message || 
                          error.message || 
                          '删除帖子时发生未知错误';
          this.$message.error(errorMsg);
        }
      }
    },
    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchTopics();
    },
  },
};
</script>

<style>
/* 新增分类区域样式 */
.category-filter-area {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  margin-bottom: 22px;
  padding: 18px;
  box-shadow: 0 2px 12px rgba(74, 144, 226, 0.1);
  border: 1px solid #d4e6f7;
}

.category-title {
  font-size: 18px;
  font-weight: 700;
  color: #2c5282;
  margin-bottom: 10px;
}

.category-divider {
  height: 1px;
  background: #e0f2fe;
  margin: 10px 0;
}

.category-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.category-btn {
  background: rgba(74, 144, 226, 0.1);
  color: #2c5282;
  border-radius: 18px;
  font-weight: 500;
  border: 1px solid #d4e6f7;
  padding: 8px 16px;
  margin-bottom: 8px;
  transition: all 0.3s;
  cursor: pointer;
}

.category-btn.active, .category-btn:hover {
  background: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

/* 更新分页样式 */
.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 卡片样式 */
.el-card {
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.el-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 18px rgba(74, 144, 226, 0.15);
}

/* 按钮样式 */
.button {
  width: 100px;
  text-align: center;
}

/* 评论详情样式 */
.comment-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #f8fafc;
}

.comment-header {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.commenter-id {
  font-weight: bold;
}

.comment-content {
  position: relative;
  font-size: 14px;
  padding-bottom: 20px;
}

.comment-time {
  position: absolute;
  bottom: 0;
  right: 0;
  font-size: 12px;
  color: #999;
}

/* 搜索按钮样式 */
.search-button {
  background-color: #32b1ec;
  color: #333;
  border: 1px solid #5795d4;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-button:hover {
  background-color: #618eba;
}

.search-button:active {
  background-color: #3389cb;
}

/* 富文本内容样式 */
.comment-content img {
  max-width: 100%;
  height: auto;
}

.comment-content pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 3px;
  overflow-x: auto;
}

.comment-content code {
  font-family: monospace;
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 3px;
}

.comment-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 10px;
  margin-left: 0;
  color: #777;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-buttons {
    justify-content: center;
  }
  
  .search-button {
    width: 100%;
    margin-top: 10px;
  }
  
  .el-input {
    width: 100% !important;
    float: none !important;
  }
}
</style>